package models

import (
	"fmt"
	"ginstudydemo.com/main/dao"
	"strconv"
	"strings"
)

type ITopicModel interface {
	CreateTestDataHandler()
}

type TopicModel struct{}

func NewTopicModel() *TopicModel {
	return &TopicModel{}
}

// GetUsePage 分页获取指定分类资源数据
// GetUsePage 分页获取指定分类专题数据
func (u TopicModel) GetUsePage(query TopicPageParams, pageParams PaginationParams) ([]TopicRes, int64, int, int, error) {
	topics := make([]TopicRes, 0)

	model := dao.Db.Debug().Table("topic r").
		Select("r.*, rt.name as category_name").
		Joins("LEFT JOIN topic_type rt ON r.category_id = rt.id").
		Where("r.is_deleted = ?", 0)

	// 是否获取子集分类数据
	if query.IsSubCate {
		var flatCategories []CategoryAndResRecursionData
		categoryIDsRECURSIVE := strings.Split(query.CategoryId, ",")

		errRECURSIVE := dao.Db.Debug().Raw(`
            WITH RECURSIVE cte AS (
                SELECT * FROM topic_type WHERE id IN ?
                UNION ALL
                SELECT c.* FROM topic_type c
                INNER JOIN cte ON c.parent_id = cte.id
            )
            SELECT * FROM cte WHERE is_deleted = 0;
        `, categoryIDsRECURSIVE).Scan(&flatCategories).Error
		if errRECURSIVE != nil {
			return nil, 0, 0, 0, errRECURSIVE
		}

		if len(flatCategories) > 0 {
			var categoryIDs []int64
			for _, cat := range flatCategories {
				categoryIDs = append(categoryIDs, cat.ID)
			}
			model = model.Where("r.category_id IN ?", categoryIDs)
		}
	} else if query.CategoryId != "" {
		categoryIDs := strings.Split(query.CategoryId, ",")
		model = model.Where("r.category_id IN ?", categoryIDs)
	}

	// 专题内容类型筛选
	if query.ContentType != "" {
		model = model.Where("r.content_type = ?", query.ContentType)
	}

	// 专题位置筛选
	if query.Location != "" {
		model = model.Where("r.location = ?", query.Location)
	}

	// 获取总数
	var total int64
	if err := model.Count(&total).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	// 分页查询
	offset := (pageParams.PageNum - 1) * pageParams.PageSize
	if err := model.Limit(pageParams.PageSize).Offset(offset).Scan(&topics).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	// 如果传入了userId，查询用户的点赞和收藏状态
	if query.UserID != "" {
		userId, err := strconv.ParseInt(query.UserID, 10, 64)
		if err != nil {
			return nil, 0, 0, 0, fmt.Errorf("invalid user id")
		}

		// 获取所有专题ID
		var topicIDs []int64
		for _, topic := range topics {
			topicIDs = append(topicIDs, topic.ID)
		}

		// 批量查询点赞状态
		likeMap := make(map[int64]bool)
		if len(topicIDs) > 0 {
			var likes []struct {
				TargetID int64
			}
			err := dao.Db.Table("user_like").
				Select("target_id").
				Where("user_id = ? AND target_id IN ? AND target_type = ? AND is_deleted = 0",
					userId, topicIDs, 2). // 2表示专题类型
				Find(&likes).Error
			if err != nil {
				return nil, 0, 0, 0, err
			}
			for _, like := range likes {
				likeMap[like.TargetID] = true
			}
		}

		// 批量查询收藏状态
		collectMap := make(map[int64]bool)
		if len(topicIDs) > 0 {
			var collects []struct {
				TopicID int64
			}
			err := dao.Db.Table("user_topic").
				Select("topic_id").
				Where("user_id = ? AND topic_id IN ? AND is_deleted = 0",
					userId, topicIDs).
				Find(&collects).Error
			if err != nil {
				return nil, 0, 0, 0, err
			}
			for _, collect := range collects {
				collectMap[collect.TopicID] = true
			}
		}

		// 设置isLike和isCollect字段
		for i := range topics {
			topics[i].IsLike = likeMap[topics[i].ID]
			topics[i].IsCollect = collectMap[topics[i].ID]
		}
	}

	return topics, total, pageParams.PageNum, pageParams.PageSize, nil
}
